package org.zjx.core;

import lombok.SneakyThrows;
import org.zjx.resource.IBaseConfig;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class GameManager {
    private final ExecutorService threadPool;
    private final int targetThreadCount;
    private final AtomicBoolean isShuttingDown = new AtomicBoolean(false); // 新增关闭状态标志
    private final ConcurrentMap<String, GameThread> activeThreads = new ConcurrentHashMap<>();
    private final AtomicInteger threadCounter = new AtomicInteger(1);

    public GameManager(IBaseConfig config) {
        this.targetThreadCount = config.gameThreadSize();
        this.threadPool = Executors.newFixedThreadPool(this.targetThreadCount);
    }

    @SneakyThrows
    public synchronized void start() {
        if (isShuttingDown.get()) {
            System.out.println("[管理器] 服务正在运行或关闭中，无法重复启动");
            return;
        }

        System.out.printf("[管理器] 正在启动 %d 个游戏线程...%n", targetThreadCount);

        for (int i = 0; i < targetThreadCount; i++) {
            startNewThread();
        }
    }

    private void startNewThread() {
        if (isShuttingDown.get()) {
            System.out.println("[管理器] 正在关闭中，不再创建新线程");
            return;
        }

        String threadId = "Thread-" + threadCounter.getAndIncrement();
        GameThread gameThread = new GameThread(threadId);
        gameThread.initialize();

        activeThreads.put(threadId, gameThread);
        System.out.printf("[管理器] 创建新线程: %s%n", threadId);

        threadPool.execute(() -> {
            try {
                System.out.printf("[管理器] 启动线程: %s%n", threadId);
                gameThread.run();
            } catch (Exception e) {
                System.err.printf("[管理器] 线程 %s 异常: %s%n", threadId, e.getMessage());
            } finally {
                activeThreads.remove(threadId);
                System.out.printf("[管理器] 线程 %s 已从活跃队列移除%n", threadId);

                // 仅在未关闭状态下补充线程
                if (!isShuttingDown.get()) {
                    checkAndReplenish();
                }
            }
        });
    }

    private void checkAndReplenish() {
        if (isShuttingDown.get()) {
            return;
        }

        int needed = targetThreadCount - activeThreads.size();
        if (needed > 0) {
            System.out.printf("[管理器] 需要补充 %d 个线程%n", needed);
            for (int i = 0; i < needed; i++) {
                startNewThread();
            }
        }
    }

    public synchronized void shutdown() {
        if (isShuttingDown.get()) {
            return;
        }

        // 设置关闭标志
        isShuttingDown.set(true);
        System.out.println("[管理器] 正在关闭所有服务...");

        // 2. 停止所有活跃线程
        activeThreads.forEach((id, thread) -> {
            System.out.printf("[管理器] 停止线程: %s%n", id);
            thread.setRunning(false);
        });

        // 3. 关闭线程池
        threadPool.shutdown();

        try {
            if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) {
                System.out.println("[管理器] 强制关闭剩余线程");
                threadPool.shutdownNow();
            }
            System.out.println("[管理器] 所有服务已关闭");
        } catch (InterruptedException e) {
            threadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public int getActiveThreadCount() {
        return activeThreads.size();
    }
}